package org.example.aidemo.service.common;

import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.example.aidemo.pojo.EmailMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class QQEmailService {
    private static final Logger log = LoggerFactory.getLogger(QQEmailService.class);
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    /**
     * 发送简单文本邮件
     */
    public void sendSimpleEmail(EmailMessage emailMessage) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(emailMessage.getTo());
            message.setSubject(emailMessage.getSubject());
            message.setText(emailMessage.getContent());

            mailSender.send(message);
            log.info("QQ邮件发送成功: {} -> {}", fromEmail,emailMessage.getTo());
        } catch (Exception e) {
            log.error("QQ邮件发送失败: {}", emailMessage.getTo(), e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }
    /**
     * 发送HTML格式邮件
     */
    public void sendHtmlEmail(String to, String subject, String htmlContent) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true); // true表示发送HTML

            mailSender.send(message);
            log.info("QQ HTML邮件发送成功: {} -> {}", fromEmail, to);
        } catch (Exception e) {
            log.error("QQ HTML邮件发送失败: {}", to, e);
            throw new RuntimeException("HTML邮件发送失败", e);
        }
    }

}